package com.example.webdemo.service;

import com.example.webdemo.bean.user;
import com.example.webdemo.dao.UserDao;
import com.example.webdemo.dto.LoginRequest;
import com.example.webdemo.dto.LoginResponse;
import com.example.webdemo.util.JwtTokenUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class AuthenticationService {

    // 添加 Log4j2 日志记录器
    private static final Logger logger = LogManager.getLogger(AuthenticationService.class);

    private final UserDao userDao;

    @Autowired
    public AuthenticationService(UserDao userDao) {
        this.userDao = userDao;
    }

    public LoginResponse login(LoginRequest loginRequest) {
        // 记录登录请求
        logger.info("尝试登录用户: {}", loginRequest.getUsername());

        user user;
        try {
            logger.info("开始搜索: {}", loginRequest.getUsername());
            user = userDao.findByUsername(loginRequest.getUsername());
            if (user == null) {String errorMsg = "用户不存在: " + loginRequest.getUsername();
                logger.warn(errorMsg);
                throw new RuntimeException(errorMsg);
            }
            logger.info("数据库查询完成，用户: {}", loginRequest.getUsername());
        } catch (IncorrectResultSizeDataAccessException e) {
            if (e.getActualSize() == 0) {
                String errorMsg = "用户名不存在: " + loginRequest.getUsername();
                logger.warn(errorMsg);
                throw new RuntimeException(errorMsg);
            } else {
                String errorMsg = "存在重复用户名: " + loginRequest.getUsername();
                logger.error("{}，实际记录数: {}", errorMsg, e.getActualSize());
                throw new RuntimeException(errorMsg);
            }
        }

        // 密码验证
        logger.info("准备验证密码: {}", loginRequest.getUsername());
        if (!Objects.equals(loginRequest.getPassword(), user.getPassword())) {
            String errorMsg = "密码错误，用户: " + loginRequest.getUsername();
            logger.warn(errorMsg);
            throw new RuntimeException(errorMsg);
        }

        // 生成 JWT Token
        String token = JwtTokenUtil.generateToken(user);
        logger.info("用户 {} 登录成功，生成 Token", user.getUsername());

        // 构建响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUserId(user.getUser_id());
        response.setUsername(user.getUsername());
        response.setRealName(user.getReal_name());

        return response;
    }

    public void resetPassword(String email) {
        logger.info("尝试重置密码，邮箱: {}", email);
        // 实际密码重置逻辑将在这里实现
        // logger.info("密码重置邮件已发送至: {}", email);
    }
}